/**
 * 
 */
package com.alstudio.ui.module.recharge;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import alipay.AlixId;
import alipay.MobileSecurePayHelper;
import alipay.MobileSecurePayer;
import alipay.PartnerConfig;
import alipay.ResultChecker;
import alipay.Rsa;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.module.recharge.ChargeHttpRqWrap;
import com.alstudio.module.recharge.ComintChargeOrderHttpResultWrap;
import com.alstudio.module.recharge.RechargeHttpReqUtils;
import com.alstudio.module.recharge.RechargeHttpReqUtils.CommitRechargOrderCallback;
import com.alstudio.module.recharge.YeepayRechageCallback;
import com.alstudio.module.recharge.YeepayUtil;
import com.alstudio.pojo.module.local.RechargeInfo;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.ui.config.BaseTitleActivityConfig;
import com.alstudio.utils.android.keyboard.ALKeyBoardManager;
import com.alstudio.utils.android.net.http.HttpDataAsynHelper;
import com.alstudio.utils.android.net.http.HttpResultWrap;
import com.alstudio.utils.formater.numeric.ALNumericUtils;
import com.alstudio.utils.log.ALLog;
import com.alstudio.utils.umeng.UmengUtils;
import com.alstudio.view.dialog.AlertDialogCreator;
import com.alstudio.view.listener.AlItemOnClickListener;
import com.alstudio.view.tableview.ALTableView;
import com.alstudio.view.tableview.ALTableView.ALTableViewClickListener;
import com.alstudio.view.tableview.ViewItem;
import com.alstudio.view.toast.MyToastUtil;
import com.loovee.imaohu.R;
import com.umeng.analytics.MobclickAgent;

/**
 * 充值界面
 * 
 * @author alonso lee
 * 
 */
public class RechargeActivity extends TitleBarActivity implements
		CommitRechargOrderCallback, YeepayRechageCallback,
		ALTableViewClickListener {

	private static final int ALIPAY_PAGE_POSITION = 0;
	private static final int YEEPAY_PAGE_POSITION = 1;

	private FrameLayout spAlipayRechargeMoney, spYeePayRechargeType;
	private EditText etYeePaySerialNum, etYeePayPwd, spYeePayRechargeMoney,
			etAlipayRechargeMoney, etYeepayRechargeType;

	private int yeepayCardTypePos = -1;
	private int alipayMoneyPos = -1;

	private String mProductId = "";
	private String mOrder = "";
	private String mFee = "";
	private int mRechargingType = 0;
	private String nDuoChargeType = "";

	private static final String ALIPAY_PRODUCTION_ID = "com.blackbean.cnmeach91.pkg.gold1";

	private DigitsKeyListener numericOnlyListener = new DigitsKeyListener(
			false, true);

	private static final int SHOW_START_RECHARGE = 0;
	private static final int SHOW_RECHARGE_TIMEOUT = 1;
	private static final int SHOW_CHECK_RECHARGE_STATUS = 2;
	private static final int SHOW_CHECK_RECHARGE_STATUS_TIMEOUT = 3;

	private static final long RECHARGE_TIME_OUT = 60000;

	private static int LAST_YEEPAY_CARD_TYPE_POS = -1;
	private static String LAST_YEEPAY_SERIAL_NUMBER = "";
	private static String LAST_YEEPAY_PASSWORD = "";
	private static String LAST_YEEPAY_MONEY = "";

	private boolean isRecharging = false;

	// 支付宝充值
	public static final int ALIPAY_RECHARGE = 1;
	// 财付通充值
	public static final int TENPAY_RECHARGE = 2;
	// 充值卡充值
	public static final int CARDPAY_RECHARGE = 3;
	// 爱贝支付
	public static final int IPAY_RECHARGE = 4;
	// 银联支付
	public static final int UPPPAY_RECHARGE = 5;

	// 缺省为支付宝充值
	private int rechargeType = ALIPAY_RECHARGE;

	private final String CHANNEL_YEEPAY = "yeepay";
	private final String CHANNEL_ALIPAY = "alipay";
	private String[] items;
	private int selectPos = 0;

	private ALTableView aLTableView1;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.TitleBarActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setupView(this, getClass().getSimpleName());
		initData();
		initView();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#setupView(android.content.Context,
	 * java.lang.String)
	 */
	@Override
	protected void setupView(Context context, String name) {
		// TODO Auto-generated method stub
		super.setupView(context, name);
		setCenterTextViewMessage(R.string.TxtRechargeTyeCard);
		setTitleBarActivityContentView(R.layout.recharge_activity_layout);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#initData()
	 */
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		rechargeType = getIntent().getIntExtra("type", ALIPAY_RECHARGE);
		mProductId = this.getIntent().getStringExtra("id");

		if (LAST_YEEPAY_CARD_TYPE_POS != -1) {
			final String[] items = getResources().getStringArray(
					R.array.recharge_type);

			yeepayCardTypePos = LAST_YEEPAY_CARD_TYPE_POS;
			etYeepayRechargeType.setText(items[LAST_YEEPAY_CARD_TYPE_POS]);
		}

		if (!TextUtils.isEmpty(LAST_YEEPAY_SERIAL_NUMBER)) {
			etYeePaySerialNum.setText(LAST_YEEPAY_SERIAL_NUMBER);
		}

		if (!TextUtils.isEmpty(LAST_YEEPAY_PASSWORD)) {
			etYeePayPwd.setText(LAST_YEEPAY_PASSWORD);
		}

		if (!TextUtils.isEmpty(LAST_YEEPAY_MONEY)) {
			spYeePayRechargeMoney.setText(LAST_YEEPAY_MONEY);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	/**
	 * 返回键监听事件
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			ALLog.d("onKeyDown back");

			if (!isRecharging) {
				this.finish();
			}
			return true;
		}

		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#finish()
	 */
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		YeepayUtil.getDefaultYeepayUtil().setYeepayRechageCallback(null);
		mHandler.removeMessages(SHOW_RECHARGE_TIMEOUT);
		mHandler.removeMessages(SHOW_CHECK_RECHARGE_STATUS_TIMEOUT);
		isActivityFinishRequest = true;
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);

		switch (v.getId()) {
		case R.id.btn_yeepay_submit:

			if (ALLocalEnv.isSendXmppDataEnable()) {
				ALKeyBoardManager.dismissKeyBoard(RechargeActivity.this);
				doRecharge();
			}
			break;
		case R.id.btn_alipay_submit:
			if (ALLocalEnv.isNetworkConnected()) {
				ALKeyBoardManager.dismissKeyBoard(RechargeActivity.this);
				doAliRecharge();
			}
			break;

		case R.id.et_yeepay_recharge_type:
			items = getResources().getStringArray(R.array.recharge_type);
			showCardDialog(getResources().getString(
					R.string.TxtRechargeCardType));
			break;

		case R.id.et_alipay_recharge_money:
			showAlipayDialog(getResources().getString(
					R.string.TxtRechargeInputMoney));
			break;
		}

	}

	private void initView() {

		BaseTitleActivityConfig config = new BaseTitleActivityConfig();

		switch (rechargeType) {
		case ALIPAY_RECHARGE:
			config.setTitle(getString(R.string.TxtRechargeAlipay));
			break;
		case TENPAY_RECHARGE:
			config.setTitle(getString(R.string.TxtRechargeTenpay));
			break;
		case CARDPAY_RECHARGE:
			config.setTitle(getString(R.string.TxtRechargeCardpay));
			break;
		case IPAY_RECHARGE:
			// 爱呗支付
			// config.setTitle(getString(R.string.string_recharge_sns_pay));
			break;
		case UPPPAY_RECHARGE:
			// 楹联支付
			// config.setTitle(getString(R.string.string_recharge_bank_cardpay));
			break;
		}

		setConfig(config);

		if (rechargeType != CARDPAY_RECHARGE) {
			findViewById(R.id.not_cardpay_layout).setVisibility(View.VISIBLE);
			findViewById(R.id.cardpay_layout).setVisibility(View.GONE);
		} else {
			findViewById(R.id.cardpay_layout).setVisibility(View.VISIBLE);
			findViewById(R.id.not_cardpay_layout).setVisibility(View.GONE);
		}

		LayoutInflater layoutInflater = LayoutInflater.from(this);
		initYeePayView(layoutInflater);
		initAliPayView(layoutInflater);

	}

	private void initYeePayView(LayoutInflater layoutInflater) {
		spYeePayRechargeType = (FrameLayout) /*
											 * yeepay_page .
											 */findViewById(R.id.sp_yeepay_recharge_type);
		etYeepayRechargeType = (EditText) /*
										 * yeepay_page .
										 */findViewById(R.id.et_yeepay_recharge_type);
		spYeePayRechargeMoney = (EditText) /*
											 * yeepay_page .
											 */findViewById(R.id.sp_yeepay_recharge_money);
		etYeePaySerialNum = (EditText) /*
										 * yeepay_page .
										 */findViewById(R.id.et_yeepay_serial_num);
		etYeePayPwd = (EditText) /* yeepay_page. */findViewById(R.id.et_yeepay_pwd);

		spYeePayRechargeMoney.setKeyListener(numericOnlyListener);
		spYeePayRechargeType.setOnClickListener(this);
		etYeepayRechargeType.setOnClickListener(this);
		/* yeepay_page. */findViewById(R.id.btn_yeepay_submit)
				.setOnClickListener(this);

		etYeePaySerialNum.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				LAST_YEEPAY_SERIAL_NUMBER = s.toString();
			}
		});

		etYeePayPwd.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				LAST_YEEPAY_PASSWORD = s.toString();
			}
		});

		spYeePayRechargeMoney.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				LAST_YEEPAY_MONEY = s.toString();
			}
		});
	}

	private void initAliPayView(LayoutInflater layoutInflater) {

		spAlipayRechargeMoney = (FrameLayout) /*
											 * alipay_page .
											 */findViewById(R.id.sp_alipay_recharge_money);
		etAlipayRechargeMoney = (EditText) /*
											 * alipay_page .
											 */findViewById(R.id.et_alipay_recharge_money);

		aLTableView1 = (ALTableView) findViewById(R.id.aLTableView1);
		aLTableView1.setClickListener(this);

		// 初始化tableview
		initAliPayTableView();

		spAlipayRechargeMoney.setOnClickListener(this);
		etAlipayRechargeMoney.setOnClickListener(this);
		/* alipay_page. */findViewById(R.id.btn_alipay_submit)
				.setOnClickListener(this);
	}

	private void initAliPayTableView() {

		final String[] items = getResources().getStringArray(
				R.array.recharge_alipay_money);
		for (int i = 0; i < items.length; i++) {
			AlipayRechrageItem item = new AlipayRechrageItem(
					getApplicationContext());
			String price = getString(R.string.TxtAlipayItemGold);
			price = String.format(price,
					ALNumericUtils.parseInt(items[i], 0) * 100);
			item.setGold(price);
			price = getString(R.string.TxtAlipayItemPrice);
			price = String.format(price, ALNumericUtils.parseInt(items[i], 0));
			item.setPrice(price);
			item.setBuyTag(i);
			item.setBuyClickListener(aliPayItemBuyListener);
			ViewItem v = new ViewItem(item);
			v.setClickable(false);
			aLTableView1.addViewItem(v);

		}
		aLTableView1.commit();

	}

	private void popupYeepayRechargeType() {
		final String[] items = getResources().getStringArray(
				R.array.recharge_type);

		final AlertDialogCreator mDialogCreator = AlertDialogCreator
				.createNoButtonWithListItemDialog(this, false, items);
		mDialogCreator.setTitle(getString(R.string.TxtYeepaySelectCardType));
		mDialogCreator.setItemClickListener(new AlItemOnClickListener() {

			@Override
			public void OnClick(int which) {
				// TODO Auto-generated method stub
				if (which >= 0 && which < items.length) {
					yeepayCardTypePos = which;
					etYeepayRechargeType.setText(items[which]);

					LAST_YEEPAY_CARD_TYPE_POS = which;
				}
				mDialogCreator.dismissDialog();
			}
		});
		mDialogCreator.showDialog();

	}

	/**
	 * 显示充值卡AlertDialo
	 */
	private void showCardDialog(String title) {
		AlertDialogCreator dialog = AlertDialogCreator
				.createNoButtonWithListItemDialog(this, false, items);
		dialog.setCancelable(true);
		// dialog.setTitle(title);
		dialog.setItemClickListener(new AlItemOnClickListener() {

			@Override
			public void OnClick(int position) {
				// TODO Auto-generated method stub
				ALLog.d("选中了" + items[position]);

				yeepayCardTypePos = position;
				etYeepayRechargeType.setText(items[position]);

				LAST_YEEPAY_CARD_TYPE_POS = position;
				etYeepayRechargeType.setText(items[position]);

			}
		});
		dialog.showDialog();
	}

	/**
	 * 显示支付宝AlertDialo
	 */
	private void showAlipayDialog(String title) {

		if (rechargeType == IPAY_RECHARGE) {
			items = getResources().getStringArray(R.array.recharge_iapp_money);

		} else {
			items = getResources()
					.getStringArray(R.array.recharge_alipay_money);
		}

		AlertDialogCreator dialog = AlertDialogCreator
				.createNoButtonWithListItemDialog(this, false, items);
		dialog.setCancelable(true);
		// dialog.setTitle(title);
		dialog.setItemClickListener(new AlItemOnClickListener() {

			@Override
			public void OnClick(int position) {
				// TODO Auto-generated method stub
				ALLog.d("选中了" + items[position]);
				selectPos = position;
				// updateSelectReson();
				alipayMoneyPos = selectPos;
				etAlipayRechargeMoney.setText(items[position]);

			}
		});
		dialog.showDialog();
	}

	/**
	 * 上傳訂單信息
	 * 
	 * @param type
	 * @param order
	 * @param productid
	 */
	private void sendRechargeInfo(int type, String order, String productid) {

		ChargeHttpRqWrap data = new ChargeHttpRqWrap();

		data.setToken(ALLocalEnv.getLocalEnv().getMyAccount().getToken());
		data.setUsername(ALLocalEnv.getLocalEnv().getMyAccount().getUserName());
		data.setProductId(productid);
		data.setOrderId(order);
		data.setRechargeType(type);

		switch (type) {
		case RechargeInfo.YEEPAY:
			RechargeHttpReqUtils.requestUploadYeepayOrder(data, this);
			break;
		case RechargeInfo.ALIPAY:
			RechargeHttpReqUtils.requestUploadAlipayOrder(data, this);
			break;
		}

		saveRechargeInfo(type, order, productid);

		mHandler.sendEmptyMessage(SHOW_START_RECHARGE);
		// 20S超时
		mHandler.sendEmptyMessageDelayed(SHOW_RECHARGE_TIMEOUT,
				RECHARGE_TIME_OUT);
	}

	/**
	 * 将重置信息保存到数据库
	 * 
	 * @param order
	 * @param productid
	 */
	private void saveRechargeInfo(int type, String order, String productid) {
		RechargeInfo info = new RechargeInfo();
		info.setType(type);
		info.setOrderNumber(order);
		info.setProductId(productid);
		ALLocalEnv.getLocalEnv().getDatabase().saveRechargeRecord(info);
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case SHOW_START_RECHARGE:
				showLoadingProgress();
				break;
			case SHOW_RECHARGE_TIMEOUT:
				dismissLoadingProgress();
				MyToastUtil.getInstance().showToastOnCenter(
						getString(R.string.string_connection_server_timeout));

				setRechargingState(false);
				break;
			case SHOW_CHECK_RECHARGE_STATUS:
				showLoadingProgress();
				break;
			case SHOW_CHECK_RECHARGE_STATUS_TIMEOUT:
				dismissLoadingProgress();
				// -----------------tody.yang---2013.08.29结束-------------------
				MyToastUtil.getInstance().showToastOnCenter(
						getResources().getString(
								R.string.string_connection_server_timeout));
				setRechargingState(false);
				break;
			}
		};
	};

	// ========= yeepay begin ==========
	private void doRecharge() {
		String cardType = etYeepayRechargeType.getText().toString().trim();
		String serialNum = etYeePaySerialNum.getText().toString().trim();
		String pwd = etYeePayPwd.getText().toString().trim();
		String recharge = spYeePayRechargeMoney.getText().toString().trim();

		if (cardType.length() == 0) {
			MyToastUtil.getInstance().showToastOnCenter(
					getString(R.string.TxtRechargeCardType));
			spYeePayRechargeType.requestFocus();
			return;
		}

		if (recharge.length() == 0) {
			MyToastUtil.getInstance().showToastOnCenter(
					getString(R.string.TxtYeepayRechargeInputMoney));
			spYeePayRechargeMoney.requestFocus();
			return;
		}

		if (serialNum.length() == 0) {
			MyToastUtil.getInstance().showToastOnCenter(
					getString(R.string.TxtYeepayRechargeInputCardNumber));
			etYeePaySerialNum.requestFocus();
			return;
		}

		if (pwd.length() == 0) {
			MyToastUtil.getInstance().showToastOnCenter(
					getString(R.string.TxtYeepayRechargeInputCardPassword));
			etYeePayPwd.requestFocus();
			return;
		}

		setRechargingState(true);

		mOrder = getOutTradeNo();
		mFee = recharge;
		mRechargingType = YEEPAY_PAGE_POSITION;

		ALLog.d(String.format("易寶充值哦亲：order : %s, 金额 : %s", mOrder, mFee));

		UmengUtils.markEvent(RechargeActivity.this,
				UmengUtils.Event.RECHARGE_YEEPAY, new String[] {
						UmengUtils.ArgName.PRODUCT_ID,
						UmengUtils.ArgName.RECHARGE_CARD,
						UmengUtils.ArgName.FEE }, new String[] {
						ALIPAY_PRODUCTION_ID, cardType, mFee });

		sendRechargeInfo(RechargeInfo.YEEPAY, mOrder, ALIPAY_PRODUCTION_ID);
	}

	private void submitYeepayOrder() {
		if (TextUtils.isEmpty(mOrder)) {
			return;
		}

		String serialNum = etYeePaySerialNum.getText().toString().trim();
		String pws = etYeePayPwd.getText().toString().trim();

		// int moneyPos = spRechargeMoney.getSelectedItemPosition();
		String moneyPos = spYeePayRechargeMoney.getText().toString();
		RechargeInfo info = new RechargeInfo();
		// info.setCardAmt(convertMoney(moneyPos)+"");
		info.setCardAmt(moneyPos);
		info.setCardNo(serialNum);
		info.setCardPwd(pws);
		info.setFrpId(getYeepayRechargeType(yeepayCardTypePos));
		info.setMoney(moneyPos);
		info.setOrderNumber(mOrder);
		info.setCallbackURL(ALLocalEnv.getLocalEnv().getVersionConfig()
				.getServerInfo().getChargeCallbackUrl());

		YeepayUtil.getDefaultYeepayUtil().invokeYeepayRecharge(info, this);
	}

	private String getYeepayRechargeType(int pos) {
		String type = "";

		switch (pos) {
		case 0:
			// 神州行
			type = RechargeInfo.SZX;
			break;

		case 1:
			// 联通卡
			type = RechargeInfo.UNICOM;
			break;

		case 2:
			// q币卡
			type = RechargeInfo.QQCARD;
			break;

		case 3:
			// 骏网一卡通
			type = RechargeInfo.JUNNET;
			break;

		case 4:
			// 盛大卡
			type = RechargeInfo.SNDACARD;
			break;

		case 5:
			// 网易卡
			type = RechargeInfo.NETEASE;
			break;

		case 6:
			// 完美卡
			type = RechargeInfo.WANMEI;
			break;

		case 7:
			// 征途卡
			type = RechargeInfo.ZHENGTU;
			break;

		case 8:
			// 就有卡
			type = RechargeInfo.JIUYOU;
			break;

		case 9:
			// 搜狐卡
			type = RechargeInfo.SOHU;
			break;

		case 10:
			// 天下一卡通
			type = RechargeInfo.TIANXIA;
			break;

		case 11:
			// 纵游一卡通
			type = RechargeInfo.ZONGYOU;
			break;

		case 12:
			// 天虹一卡通
			type = RechargeInfo.TIANHONG;
			break;

		case 13:
			// 易宝e卡通
			type = RechargeInfo.YPCARD;
			break;
		}

		return type;
	}

	// ========= yeepay end ==========

	// ========== alipay begin =============

	private String getAlipayRechargeMoney(int pos) {
		String value = "";

		switch (pos) {
		case 0:
			value = "10";
			break;

		case 1:
			value = "20";
			break;

		case 2:
			value = "50";
			break;

		case 3:
			value = "100";
			break;

		case 4:
			value = "200";
			break;

		case 5:
			value = "500";
			break;

		case 6:
			value = "1000";
			break;
		case 7:
			value = "2000";
			break;
		case 8:
			value = "5000";
			break;
		}

		return value;
	}

	/**
	 * 支付宝充值
	 */
	private void doAliRecharge() {
		// 检测输入金额是否合法
		String fee = getAlipayRechargeMoney(alipayMoneyPos);

		if (fee.length() < 1) {
			MyToastUtil.getInstance().showToastOnCenter(
					getString(R.string.TxtRechargeInputMoney));
			spAlipayRechargeMoney.requestFocus();
			return;
		}

		//
		// check to see if the MobileSecurePay is already installed.
		// 检测安全支付服务是否安装
		MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(this);
		boolean isMobile_spExist = mspHelper
				.detectMobile_sp(onAlipayCancelListener);
		if (!isMobile_spExist)
			return;

		// check some info.
		// 检测配置信息
		if (!checkInfo()) {
			MyToastUtil.getInstance().showCustomToastOnCenter(
					getString(R.string.TxtAlipayStartFail));

			return;
		}

		mOrder = getOutTradeNo();
		mFee = fee;
		mRechargingType = ALIPAY_PAGE_POSITION;

		ALLog.d(String.format("致富饱充值哦亲：order : %s, 金额 : %s", mOrder, mFee));

		UmengUtils.markEvent(RechargeActivity.this,
				UmengUtils.Event.RECHARGE_ALIPAY,
				new String[] { UmengUtils.ArgName.PRODUCT_ID,
						UmengUtils.ArgName.FEE }, new String[] {
						ALIPAY_PRODUCTION_ID, mFee });

		sendRechargeInfo(RechargeInfo.ALIPAY, mOrder, ALIPAY_PRODUCTION_ID);
	}

	private void launchAlipay() {
		// start pay for this order.
		// 根据订单信息开始进行支付
		try {
			// prepare the order info.
			// 准备订单信息
			String orderInfo = getOrderInfo(
					getString(R.string.TxtAlipaySubject),
					getString(R.string.TxtAlipayBody), mOrder, mFee);
			// 这里根据签名方式对订单信息进行签名
			String signType = getSignType();
			String strsign = sign(signType, orderInfo);
			// 对签名进行编码
			strsign = URLEncoder.encode(strsign);
			// 组装好参数
			String info = orderInfo + "&sign=" + "\"" + strsign + "\"" + "&"
					+ getSignType();
			// start the pay.
			// 调用pay方法进行支付
			MobileSecurePayer msp = new MobileSecurePayer();
			boolean bRet = msp.pay(info, mAlipayHandler, AlixId.RQF_PAY, this);

		} catch (Exception ex) {
			MyToastUtil.getInstance().showCustomToastOnCenter(
					getString(R.string.TxtAlipayStartFail));
		}
	}

	/**
	 * check some info.the partner,seller etc. 检测配置信息
	 * partnerid商户id，seller收款帐号不能为空
	 * 
	 * @return
	 */
	private boolean checkInfo() {
		String partner = PartnerConfig.PARTNER;
		String seller = PartnerConfig.SELLER;
		if (partner == null || partner.length() <= 0 || seller == null
				|| seller.length() <= 0)
			return false;

		return true;
	}

	/**
	 * get the selected order info for pay. 获取商品订单信息
	 * 
	 * @param position
	 *            商品在列表中的位置
	 * @return
	 */
	String getOrderInfo(String subject, String body, String orderid,
			String total_fee) {

		String strOrderInfo = "partner=" + "\"" + PartnerConfig.PARTNER + "\"";
		strOrderInfo += "&";
		strOrderInfo += "seller=" + "\"" + PartnerConfig.SELLER + "\"";
		strOrderInfo += "&";
		strOrderInfo += "out_trade_no=" + "\"" + orderid + "\"";
		strOrderInfo += "&";
		strOrderInfo += "subject=" + "\"" + subject + "\"";
		strOrderInfo += "&";
		strOrderInfo += "body=" + "\"" + body + "\"";
		strOrderInfo += "&";
		strOrderInfo += "total_fee=" + "\"" + total_fee + "\"";
		strOrderInfo += "&";
		strOrderInfo += "notify_url="
				+ "\""
				+ ALLocalEnv.getLocalEnv().getVersionConfig().getServerInfo()
						.getAlipayUrl() + "\"";

		ALLog.d("alipay order info : " + strOrderInfo);

		return strOrderInfo;
	}

	/**
	 * get the out_trade_no for an order. 获取外部订单号
	 * 
	 * @return
	 */
	String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
		String strKey = format.format(new Date());

		java.util.Random r = new java.util.Random();
		strKey = strKey + r.nextInt();
		strKey = strKey.substring(0, 15);
		return strKey;
	}

	String getOrderId() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
		Date date = new Date();
		String strKey = format.format(date);

		java.util.Random r = new java.util.Random();
		strKey = strKey + r.nextInt();
		strKey = strKey.substring(0, 10);
		return strKey;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param signType
	 *            签名方式
	 * @param content
	 *            待签名订单信息
	 * @return
	 */
	String sign(String signType, String content) {
		return Rsa.sign(content, PartnerConfig.RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 * @return
	 */
	String getSignType() {
		String getSignType = "sign_type=" + "\"" + "RSA" + "\"";
		return getSignType;
	}

	/**
	 * the OnCancelListener for lephone platform. lephone系统使用到的取消dialog监听
	 */
	public DialogInterface.OnCancelListener onAlipayCancelListener = new DialogInterface.OnCancelListener() {

		@Override
		public void onCancel(DialogInterface dialog) {
			RechargeActivity.this.onKeyDown(KeyEvent.KEYCODE_BACK, null);
		}
	};

	//
	// the handler use to receive the pay result.
	// 这里接收支付结果，支付宝手机端同步通知
	private Handler mAlipayHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			try {
				String strRet = (String) msg.obj;

				ALLog.d(strRet);// 05-09 17:08:45.280: E/AppDemo4(3358):
								// resultStatus={9000};memo={};result={partner="2088201564809153"&seller="2088201564809153"&out_trade_no="050917083121576"&subject="123456"&body="2010新款NIKE 耐克902第三代板鞋 耐克男女鞋 386201 白红"&total_fee="0.01"&notify_url="http://notify.java.jpxx.org/index.jsp"&success="true"&sign_type="RSA"&sign="d9pdkfy75G997NiPS1yZoYNCmtRbdOP0usZIMmKCCMVqbSG1P44ohvqMYRztrB6ErgEecIiPj9UldV5nSy9CrBVjV54rBGoT6VSUF/ufjJeCSuL510JwaRpHtRPeURS1LXnSrbwtdkDOktXubQKnIMg2W0PreT1mRXDSaeEECzc="}

				switch (msg.what) {
				case AlixId.RQF_PAY: {

					ALLog.d(strRet);

					// 从通知中获取参数
					try {
						// 获取交易状态，具体状态代码请参看文档
						String tradeStatus = "resultStatus=";
						int imemoStart = strRet.indexOf("resultStatus=");
						imemoStart += tradeStatus.length();
						int imemoEnd = strRet.indexOf(";memo=");
						tradeStatus = strRet.substring(imemoStart, imemoEnd);

						// 对通知进行验签
						ResultChecker resultChecker = new ResultChecker(strRet);

						int retVal = resultChecker.checkSign();
						boolean isPayOk = resultChecker.isPayOk();

						ALLog.d(String
								.format("致富饱支付结果：tradeStatus %s, retVal %d, isPayOk %b",
										tradeStatus, retVal, isPayOk));

						// 返回验签结果以及交易状态
						// && retVal == ResultChecker.RESULT_CHECK_SIGN_SUCCEED
						if (tradeStatus.contains("9000") && isPayOk) {
							// 支付成功

							mHandler.sendEmptyMessage(SHOW_CHECK_RECHARGE_STATUS);
							// 20S超时
							mHandler.sendEmptyMessageDelayed(
									SHOW_CHECK_RECHARGE_STATUS_TIMEOUT,
									RECHARGE_TIME_OUT);

							// TODO 查询交易状态
							ALLog.d("支付成功啦。去问服务器要金币");
							Intent intent = new Intent(/*
														 * Events.
														 * ACTION_REQUEST_CHECK_RECHARGE_STATUS
														 */);
							intent.putExtra("order", mOrder);

							// sendBroadcast(intent);
							nDuoChargeType = CHANNEL_ALIPAY;
							getRechargeGold(mOrder, true, 10);

						} else {
							// 支付失败
							ALLog.d("怎么支付就失败了啊。没天理啊。");
							ALLog.d(strRet);

							String text = getAlipayTradeStatusText(tradeStatus);
							MyToastUtil.getInstance().showToastOnCenter(text);
						}

					} catch (Exception e) {
						ALLog.d("你妹的致富饱异常啦。" + strRet);
						e.printStackTrace();

						String text = getString(R.string.TxtRechargeException);
						MyToastUtil.getInstance().showToastOnCenter(text);
					}
				}
					break;
				}

				super.handleMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private String getAlipayTradeStatusText(String status) {
		String text;

		if (status.contains("4000")) {
			text = getString(R.string.TxtAlipayStatus4000);
		} else if (status.contains("4001")) {
			text = getString(R.string.TxtAlipayStatus4001);
		} else if (status.contains("4003")) {
			text = getString(R.string.TxtAlipayStatus4003);
		} else if (status.contains("4004")) {
			text = getString(R.string.TxtAlipayStatus4004);
		} else if (status.contains("4005")) {
			text = getString(R.string.TxtAlipayStatus4005);
		} else if (status.contains("4006")) {
			text = getString(R.string.TxtAlipayStatus4006);
		} else if (status.contains("4010")) {
			text = getString(R.string.TxtAlipayStatus4010);
		} else if (status.contains("6000")) {
			text = getString(R.string.TxtAlipayStatus6000);
		} else if (status.contains("6001")) {
			text = getString(R.string.TxtAlipayStatus6001);
		} else if (status.contains("6002")) {
			text = getString(R.string.TxtAlipayStatus6002);
		} else {
			text = getString(R.string.TxtRechargeFailed);
		}

		return text;
	}

	// ========== alipay end =============

	private void setRechargingState(boolean recharging) {
		isRecharging = recharging;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.module.recharge.RechargeHttpReqUtils.CommitRechargOrderCallback
	 * #onSuccess(com.alstudio.module.recharge.ComintChargeOrderHttpResultWrap)
	 */
	@Override
	public void onSuccess(ComintChargeOrderHttpResultWrap result) {
		// TODO Auto-generated method stub
		mHandler.removeMessages(SHOW_RECHARGE_TIMEOUT);
		switch (result.getRechargeType()) {
		case RechargeInfo.ALIPAY:
			dismissLoadingProgress();
			launchAlipay();
			break;
		case RechargeInfo.YEEPAY:
			submitYeepayOrder();
			break;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.module.recharge.RechargeHttpReqUtils.CommitRechargOrderCallback
	 * #onFailure(int, java.lang.Throwable)
	 */
	@Override
	public void onFailure(int statusCode, Throwable error) {
		// TODO Auto-generated method stub
		mHandler.removeMessages(SHOW_RECHARGE_TIMEOUT);
		dismissLoadingProgress();
		MyToastUtil.getInstance().showCenterToastOnCenter(
				"创建订单失败 " + error.toString());
		setRechargingState(false);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.module.recharge.YeepayRechageCallback#
	 * yeepaySubmitRechargeOrderEvent(int, java.lang.String)
	 */
	@Override
	public void yeepaySubmitRechargeOrderEvent(int code, String order) {
		// TODO Auto-generated method stub

		switch (code) {
		case 1:
			// 提交成功
			getRechargeGold(order, true, 10);
			ALLog.d("提交充值订单到易宝成功");
			break;
		case -1:
			// 签名较验失败或未知错误
		case 2:
			// 卡密成功处理过或者提交卡号过于频繁
		case 5:
			// 卡数量过多，目前最多支持10张卡
		case 11:
			// 订单号重复
		case 66:
			// 支付金额有误
		case 95:
			// 支付方式未开通
		case 112:
			// 业务状态不可用，未开通此类卡业务
		case 8001:
			// 卡面额组填写错误
		case 8002:
			// 卡号密码为空或者数量不相等（使用组合支付时）
			ALLog.d("提交充值订单到易宝失败" + (code));
			break;
		}
	}

	private boolean isActivityFinishRequest = false;
	private int checkRechargeStatusCount = -1;

	/**
	 * 易宝充值，循环查服务器是否到账
	 * 
	 * @param orderId
	 * @param repeat
	 * @param repeatCount
	 */
	private void getRechargeGold(final String orderId, final boolean repeat,
			final int repeatCount) {
		if (isActivityFinishRequest)
			return;
		if (checkRechargeStatusCount == -1) {
			checkRechargeStatusCount = repeatCount;
		}
		ChargeHttpRqWrap data = new ChargeHttpRqWrap();

		data.setToken(ALLocalEnv.getLocalEnv().getMyAccount().getToken());
		data.setUsername(ALLocalEnv.getLocalEnv().getMyAccount().getUserName());
		data.setOrderId(orderId);

		ALLog.d("开始重新获取未成功的充值订单" + orderId);
		HttpDataAsynHelper.Callback callback = new HttpDataAsynHelper.Callback() {

			@Override
			public void onSuccess(HttpResultWrap data) {
				// TODO Auto-generated method stub
				ComintChargeOrderHttpResultWrap result = (ComintChargeOrderHttpResultWrap) data;

				if (data.getResultCode() == 1) {
					ALLog.d("重新充值成功");
					new Thread() {
						public void run() {
							ALLocalEnv.getLocalEnv().getDatabase()
									.deletRechargeRecordByOrderId(orderId);
						};
					}.start();
				} else {
					ALLog.d("充值失败 " + result.getResultCode());
					if (data.getResultCode() == 0) {
						if (repeat) {
							if (checkRechargeStatusCount >= 0) {
								checkRechargeStatusCount--;
								new Thread() {
									public void run() {
										try {
											Thread.sleep(5000);
										} catch (InterruptedException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										getRechargeGold(orderId, repeat, 0);
									};
								}.start();
							}
						}
					}
				}
				parseChargeResult(result.getResultCode(),
						result.getCardstatus());
			}

			@Override
			public void onSuccess(Bundle data) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onError(Exception e) {
				// TODO Auto-generated method stub
				// if(repeat)
				// {
				// getYeePayCoin(orderId,repeat);
				// }
			}
		};

		HttpDataAsynHelper.requestRechargeStatus(data, callback);
	}

	private void parseChargeResult(int code, String cardStatus) {
		switch (code) {
		case 1:
			mhandler.post(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					dismissLoadingProgress();
					// 充值成功
					MyToastUtil.getInstance().showToastOnCenter(
							getString(R.string.TxtRechargeSuccess));

					LAST_YEEPAY_CARD_TYPE_POS = -1;
					LAST_YEEPAY_SERIAL_NUMBER = "";
					LAST_YEEPAY_PASSWORD = "";
					LAST_YEEPAY_MONEY = "";

					setRechargingState(false);

					finish();

				}
			});
			break;
		case 3:
			dismissLoadingProgress();
			// 充值失败
			MyToastUtil.getInstance().showToastOnCenter(
					getString(R.string.TxtRechargeFail) + cardStatus);
			setRechargingState(false);
			break;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.view.tableview.ALTableView.ALTableViewClickListener#onClick
	 * (int)
	 */
	@Override
	public void onClick(int index) {
		// TODO Auto-generated method stub

	}

	private OnClickListener aliPayItemBuyListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (ALLocalEnv.isNetworkConnected()) {
				int index = (Integer) v.getTag();
				ALLog.d("点击了 " + index);
				alipayMoneyPos = index;
				doAliRecharge();
			}
		}
	};

}
